/**
 * table的通用方法
 */
import _ from 'lodash';

export function tableDecorator(target) {
	const { componentWillMount, componentWillReceiveProps, componentDidUpdate, query } = target.prototype;
	target.prototype.componentWillMount = function () {
		// 覆盖再先执行原来的componentWillMount
		if (componentWillMount) componentWillMount.call(this);
		// 绑定this
		this.pageChange = this.pageChange.bind(this);
		this.pagesizgeChange = this.pagesizgeChange.bind(this);
		// 通用逻辑
		this.query();
	};
	target.prototype.componentWillReceiveProps = function (nextProps) {
		// 覆盖再先执行原来的componentWillMount
		if (componentWillReceiveProps) componentWillReceiveProps.call(this, nextProps);
		// 通用逻辑
		if (!_.isEqual(nextProps.queryData, this.props.queryData)) {
			this.setState({ current: 1 });
		}
	};
	target.prototype.componentDidUpdate = function (prevProps, prevState) {
		// 覆盖再先执行原来的componentWillMount
		if (componentDidUpdate) componentDidUpdate.call(this, prevProps, prevState);
		// 通用逻辑
		const { current, size } = this.state;
		if (!_.isEqual(prevProps.queryData, this.props.queryData) || current !== prevState.current || size !== prevState.size) {
			this.query();
		}
	};

	// 通用方法
	target.prototype.pageChange = function (current) {
		this.setState({ current });
	};

	target.prototype.pagesizgeChange = function (current, size) {
		this.setState({ current: 1, size });
	};

	target.prototype.query = function () {
		if (query) return;
		// 请求数据
		const { dispatch, queryData } = this.props;
		const { current, size, defaultQuery } = this.state;
		dispatch({
			type: this.queryApi,
			payload: { ...defaultQuery, query: queryData, current, size }
		});
	};
}
